package com.ch.mafia.service;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.ch.mafia.base.BaseDao;
import com.ch.mafia.base.BaseServlet;
import com.ch.mafia.tools.DateHelper;

/**
 * Servlet implementation class RegisterService
 */
public class RegisterService extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		JSONObject jsonParams =new JSONObject();
		JSONObject jsonResult=new JSONObject();
		try{
			if(request.getParameter("json")!=null){
				jsonParams=new JSONObject(request.getParameter("json"));
				System.out.println("jsonParams:"+jsonParams.toString());
			}
			String userName = jsonParams.getString("username");
			String nickName = jsonParams.getString("nickname");
			BaseDao baseDao =new BaseDao();
			JSONObject jsonObject = baseDao.queryBean("s_user", null, "username = ? or nickname=?", new String[]{userName,nickName});
			if(jsonObject!=null){
				if(userName.equals(jsonObject.getString("username"))){
					jsonResult.put("message","用户名已存在");
				}else{
					jsonResult.put("message","昵称已存在");
				}
				jsonResult.put("result",MESSAGE);
			}else{
				jsonParams.put("lastconnecttime", new Date().getTime());
				jsonParams.put("isonline","1");
				jsonParams.put("registertime", DateHelper.getNow());
				Integer id = baseDao.add(jsonParams);
				jsonResult.put("id", id);
				jsonResult.put("result",SUCCESS);
			}
		}catch (Exception e) {
			e.printStackTrace();
			try{
				jsonResult.put("result",FAIL);
			}catch (Exception ex) {
				ex.printStackTrace();
			}
			
		}
		response.getWriter().print(jsonResult.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
